<template>
  <div class="auth-contail">
    <van-nav-bar class="header"
                 :title="title"
                 left-arrow
                 @click-left="goBack">
      <span slot="right"
            @click="logout"
            v-if="type===0">退出</span>
    </van-nav-bar>
    <div class="weaper">
      <van-cell-group class="fengniao-form form">
        <div class="form-items">
          <van-field center
                     class="form-item"
                     label="姓名"
                     v-model="form.name"
                     placeholder="请输入姓名"
                     :disabled="disabled" />

          <van-select-field center
                            class="form-item"
                            label="用户类型"
                            dic-name="relation"
                            placeholder="选择用户类型"
                            v-model="form.relation"
                            :disabled="disabled" />
          <van-select-field center
                            class="form-item"
                            label="小区"
                            v-model="form.communityId"
                            placeholder="请选择小区"
                            @change="communityChange"
                            :list="communityList"
                            :props="communityProps"
                            :disabled="disabled" />
          <van-select-field center
                            class="form-item"
                            label="楼栋"
                            v-model="form.buildingId"
                            placeholder="请选择楼栋"
                            @change="buildingChange"
                            :list="buildingList"
                            :props="buildingProps"
                            :disabled="disabled" />
          <van-select-field center
                            class="form-item"
                            label="单元"
                            v-model="form.unitId"
                            placeholder="请选择单元"
                            @change="unitChange"
                            :list="unitList"
                            :props="unitprops"
                            v-if="status"
                            :disabled="disabled" />
          <van-select-field center
                            class="form-item"
                            label="房间"
                            v-model="form.houseId"
                            placeholder="请选择房间"
                            :list="houseList"
                            :props="houseprops"
                            :disabled="disabled" />
        </div>
        <div class="form-items">
          <van-field center
                     class="form-item"
                     label="预留手机号"
                     v-model="form.phone"
                     :disabled="disabled"
                     placeholder="请输入预留手机号" />
        </div>
      </van-cell-group>
    </div>
    <van-button class="submit"
                type="primary"
                @click="submit">绑定</van-button>
  </div>
</template>

<script>
import vanSelectField from '@/components/select/main';
import { asyncValidator } from '@/util/validate';
import {
  getCommunityList,
  getBuildingList,
  getUnitList,
  getHouseList,
  addCommunity,
} from '@/api/community/';

import baseCommon from '@/mixins/common';
import { validatenull } from '@/util/validate';

export default {
  mixins: [baseCommon()],
  components: {
    vanSelectField,
  },
  data () {
    return {
      type: 0,
      title: '信息绑定',
      disabled: false,
      form: {
        name: '',
        relation: '',
        communityId: '',
        buildingId: '',
        unitId: '',
        houseId: '',
        phone: '',
      },
      status: true,
      communityList: [],
      buildingList: [],
      unitList: [],
      houseList: [],
      communityProps: {
        value: 'id',
        label: 'name',
      },
      buildingProps: {
        value: 'id',
        label: 'buildingName',
      },
      unitprops: {
        value: 'id',
        label: 'unitName',
      },
      houseprops: {
        value: 'id',
        label: 'houseName',
      },
    };
  },
  created () {
    this.init();
  },
  methods: {
    logout () {
      this.$store.dispatch('FedLogOut')
        .then(() => {
          this.$router.replace({ path: '/user/index' });
        });
    },
    submit () {
      const safe = this;
      const rules = {
        name: { type: 'string', required: true, message: '请输入姓名' },
        relation: { type: 'string', required: true, message: '请选择类型' },
        communityId: { type: 'string', required: true, message: '请选择小区' },
        buildingId: { type: 'string', required: true, message: '请选择楼' },
        unitId (rule, value, callback, source, options) {
          const errors = [];
          if (safe.status && validatenull(value)) {
            errors.push('请选择单元');
          }
          callback(errors);
        },
        houseId: { type: 'string', required: true, message: '请选择房间' },
        phone: { type: 'string', required: true, message: '请输入手机号' },
      };
      asyncValidator(rules, this.form)
        .then(() => addCommunity(this.form))
        .then((res) => {
          const data = res.data;
          const success = data.success;
          const msg = data.msg;
          if (!success) return Promise.reject([{ message: msg }]);
          return this.$store.dispatch('GetUserInfo');
        })
        .then(() => {
          this.$message.success({
            message: '绑定成功',
            duration: 1500,
          });
          setTimeout(() => {
            if (this.type === 0) {
              this.goPage('/index/main');
            } else {
              this.goBack();
            }
          }, 500);
        })
        .catch((errors) => {
          this.$message.warning({
            message: errors[0].message,
            duration: 1500,
          });
        });
    },
    init () {
      this.type = this.$route.query.type || 0;
      if (this.type === 1) {
        this.title = '小区新增';
      }
      this.getCommunityList();
      if (!validatenull(this.form.communityId)) {
        this.getBuildingList();
      }
      if (!validatenull(this.form.buildingId)) {
        this.getUnitList();
      }
      if (!validatenull(this.form.unitId)) {
        this.getHouseList();
      }
    },
    communityChange (val) {
      this.form.buildingId = '';
      this.form.unitId = '';
      this.form.houseId = '';
      if (!validatenull(this.form.communityId)) this.getBuildingList();
    },
    buildingChange (val) {
      this.form.unitId = '';
      this.form.houseId = '';
      if (!validatenull(this.form.buildingId)) this.getUnitList();
    },
    unitChange (val) {
      this.form.houseId = '';
      if (!validatenull(this.form.unitId)) this.getHouseList();
    },
    getHouseList () {
      getHouseList(this.form.unitId).then((res) => {
        const data = res.data;
        this.houseList = data;
      });
    },
    getUnitList () {
      getUnitList(this.form.buildingId).then((res) => {
        const data = res.data;
        this.status = Number(data.attributes.existUnit) === 1;
        const obj = data.obj;
        if (this.status) {
          this.unitList = obj;
        } else {
          this.houseList = obj;
        }
      });
    },
    getBuildingList () {
      getBuildingList(this.form.communityId).then((res) => {
        const data = res.data;
        this.buildingList = data;
      });
    },
    getCommunityList () {
      getCommunityList().then((res) => {
        const data = res.data;
        this.communityList = data;
      });
    },
  },
};
</script>

<style scoped>
.submit {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 55px;
  border-radius: 0;
}
</style>
